package com.antdesignbackend.backend.webAPP;

import com.antdesignbackend.backend.animalNumber.entity.AnimalNumber;
import com.antdesignbackend.backend.animalNumber.service.AnimalNumberService;
import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.CalendarDate;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.common.web.BaseController;
import com.antdesignbackend.backend.entity.Production;
import com.antdesignbackend.backend.entity.entityVo.ProductionVo;
import com.antdesignbackend.backend.service.ProductionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RequestMapping("/productionAPP")
@Controller
public class
ProductionAPPController {

    @Autowired
    ProductionService productionService;

    @Autowired
    AnimalNumberService animalNumberService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private Integer menuId;


    /**
     * 分页查询
     * @param productionVo
     * @return
     */
    @PostMapping("/tableSearch")
    @ResponseBody
    public ReturnVO tableSearch(@RequestBody ProductionVo productionVo) {
        ReturnVO result = new ReturnVO();
        List<ProductionVo> datalist=new ArrayList<>();
        try {
            QueryWrapper<ProductionVo> queryWrapper = new QueryWrapper<>();
            if (productionVo.getSituation() != null && !productionVo.getSituation().equals("")){
                queryWrapper.eq("situation",productionVo.getSituation());

            }
            if (productionVo.getTimeInterval() != null && !productionVo.getTimeInterval().equals("")){
                String[] str=productionVo.getTimeInterval().split(" - ");
                String star=str[0];
                String end=str[1];
                queryWrapper.between("changeTime",star,end);
            }
            queryWrapper.orderByDesc("changeTime");
            queryWrapper.eq("A.eid",productionVo.getEid());
            //先统计满足条件的数据总数，因为sql 不包括排序
            int total=productionService.count(queryWrapper);
            result.setTotal(total);
            //再查询
            if(total>0)
            {
                datalist= productionService.search(queryWrapper,new Page<>(productionVo.getPageIndex(),productionVo.getPageSize()));
            }
            result.setData(datalist);
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return result;
    }
    @PostMapping("/tableSearchMe/{eid}")
    @ResponseBody
    public ReturnVO tableSearchMe(@PathVariable("eid") int eid) {
        ReturnVO result = new ReturnVO();
        List<ProductionVo> datalist=new ArrayList<>();
        try {
            QueryWrapper<ProductionVo> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("changeTime");
            queryWrapper.eq("A.eid",eid);
            //先统计满足条件的数据总数，因为sql 不包括排序
            int total=productionService.count(queryWrapper);
            result.setTotal(total);
            //再查询
            if(total>0)
            {
                datalist= productionService.search(queryWrapper,new Page<>(1,10));
            }
            result.setData(datalist);
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return result;
    }
    /**
     * 修改/新增操作的保存
     */
    @PostMapping("/save")
    @ResponseBody
    public ReturnVO save(@RequestBody ProductionVo productionVo) throws Exception {
        ReturnVO result = new ReturnVO();
        boolean b = false;
        if(productionVo.getProductionId()==0){
            productionVo.setUid(productionVo.getUid());
            productionVo.setEid(productionVo.getEid());
            productionVo.setAnimalType(productionVo.getAnimalType());
            productionVo.setCreateTime(new Date());
            b=productionService.save(productionVo);
            AnimalNumber animalNumber=new AnimalNumber();
            animalNumber.setSpecies(productionVo.getMale());
            animalNumber.setReserve(productionVo.getFemale());
            animalNumber.setMenstruation(productionVo.getBreedFemale());
            animalNumber.setLactation(productionVo.getLactation());
            animalNumber.setConservation(productionVo.getConservation());
            animalNumber.setCommodity(productionVo.getGrow());animalNumber.setLivestock(productionVo.getNumber());
            animalNumber.setEid(productionVo.getEid());
            animalNumber.setAnimalType(productionVo.getAnimal());
            animalNumber.setStarTime(productionVo.getChangeTime());
            animalNumber.setConservationTime(CalendarDate.addDate(animalNumber.getStarTime(),"day",productionVo.getDay1()));
            animalNumber.setGrowTime(CalendarDate.addDate(animalNumber.getStarTime(),"day",productionVo.getDay1()+productionVo.getDay2()));
            animalNumber.setCreateTime(new Date());
            animalNumber.setChannel(2);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            animalNumber.setBatchNumber(simpleDateFormat.format(animalNumber.getStarTime()));
            animalNumber.setPid(productionVo.getProductionId());
            animalNumberService.save(animalNumber);
        }else{
            QueryWrapper<AnimalNumber> animalNumberQueryWrapper=new QueryWrapper<>();
            animalNumberQueryWrapper.eq("pid",productionVo.getProductionId()).eq("channel",2);
            AnimalNumber animalNumber=animalNumberService.getOne(animalNumberQueryWrapper); //动物明细表对象
            Production oldProduction=productionService.getById(productionVo.getProductionId());   //旧的生产表对象
            UpdateWrapper<AnimalNumber> animalNumberUpdateWrapper=new UpdateWrapper<>();
            if(productionVo.getAnimal()==1){
                animalNumberUpdateWrapper.set("species",animalNumber.getSpecies()-oldProduction.getMale()+productionVo.getMale())
                        .set("reserve",animalNumber.getReserve()-oldProduction.getFemale()+productionVo.getFemale())
                        .set("menstruation",animalNumber.getMenstruation()-oldProduction.getBreedFemale()+productionVo.getBreedFemale())
                        .set("lactation",animalNumber.getLactation()-oldProduction.getLactation()+productionVo.getLactation())
                        .set("conservation",animalNumber.getConservation()-oldProduction.getConservation()+productionVo.getConservation())
                        .set("commodity",animalNumber.getCommodity()-oldProduction.getGrow()+productionVo.getGrow())
                        .eq("pid",productionVo.getProductionId()).eq("channel",2);
            }else{
                animalNumberUpdateWrapper.set("livestock",animalNumber.getLivestock()-oldProduction.getNumber()+productionVo.getNumber())
                        .eq("pid",productionVo.getProductionId()).eq("channel",2);
            }
            b=productionService.updateById(productionVo);
            animalNumberService.update(animalNumberUpdateWrapper);
        }
        if(b==true){
            result.setMessage("保存成功！");
            result.setCode("200");
        }
        else
        {
            result.setMessage("保存失败！");
            result.setCode("500");
        }
        return result;
    }
    /**
     * 删除
     * @param
     * @return
     */
    @DeleteMapping("/deleteById/{id}")
    @ResponseBody
    public ReturnVO deleteById(@PathVariable Serializable id) {
        ReturnVO result = new ReturnVO();
        if (productionService.removeById(Integer.parseInt(id.toString())) == true) {
            result.setMessage("删除成功");
            QueryWrapper<AnimalNumber> animalNumberQueryWrapper=new QueryWrapper<>();
            animalNumberQueryWrapper.eq("pid",id).eq("channel",2);
            animalNumberService.remove(animalNumberQueryWrapper);
        } else {
            result.setMessage("删除失败");
            result.setCode("0");
        }
        return result;
    }
}

